package softtech.apps.callblocker;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import softtech.apps.utility.ApplicationConstants;
import softtech.apps.callblocker.model.BlackListItem;
import softtech.apps.callblocker.model.ContentSmsBlock;
import softtech.apps.callblocker.model.DatabaseHanler;
import softtech.apps.callblocker.model.HeaderPhone;
import softtech.apps.callblocker.model.Setting;
import softtech.apps.callblocker.model.SmsBlockedItem;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class ReceiveSMS extends BroadcastReceiver {
	final String TAG = "RECEIVE SMS";
	Context mContext;
	/** Called when the activity is first created. */
	final String ACTION = "android.provider.Telephony.SEND_SMS";
	public static int MSG_TPE = 0;
	String MSG_TYPE;
	Calendar dt;
	/**
	 * Content messenger receive
	 */
	String messageBody = null;
	/**
	 * phone number receive
	 */
	String phoneNumber = null;
	/**
	 * check block messenger
	 */
	int checkblock = 0;
	/**
	 * check save app
	 */
	int saveapp = 0;

	/**
	 * send broadcast sms when have unknow contact
	 */
	void updateViewWhenReceiveSMS() {
		Log.e(TAG , "da send broadcast");
		Intent intent_sms = new Intent(ApplicationConstants.TAG_BROADCAST);
		intent_sms.putExtra("receivetype", 2);
		intent_sms.putExtra("phonenumber", phoneNumber);
		intent_sms.putExtra("messenger", messageBody);
		intent_sms.putExtra("saveapp", saveapp);
		intent_sms.putExtra("modesms", getSettingDefaultModeSMS());
		;
		mContext.sendBroadcast(intent_sms);
	}

	@SuppressLint("NewApi")
	@Override
	public void onReceive(Context context, Intent intent) {
		
		mContext = context;
		DatabaseHanler db = new DatabaseHanler(context);
		MSG_TYPE = intent.getAction();
		
		if (MSG_TYPE.equals("android.provider.Telephony.SMS_RECEIVED")) {
			try{
				dt = Calendar.getInstance();
				Bundle bundle = intent.getExtras();
				SmsMessage[] msgs = null;
				Object[] pdus = (Object[]) bundle.get("pdus");
				messageBody ="";
				msgs = new SmsMessage[pdus.length];
				Log.e(TAG , "1");
				for (int i = 0; i < msgs.length; i++) {
					// Get All SMS
					msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
					messageBody = messageBody + msgs[i].getMessageBody();
					System.out.println(messageBody);
					if(msgs[i] != null){
						phoneNumber = msgs[i].getOriginatingAddress();
					}
					
				}
				Log.e(TAG , " tin nhan =" + messageBody + " sodt = "+ phoneNumber);
				//
				checkblock = 0;
				if ((getSettingDefaultModeSMS() & 15) != 0) {
					// block black list
					BlockBlacklist(phoneNumber);
					//
					// block unknow number
					//
					if ((getSettingDefaultSMS() & 1) == 1) {
						BlockUnknowContact(phoneNumber);
					}
					//
					// block content sms
					//
					if ((getSettingDefaultSMS() & 2) == 2) {
						ArrayList<ContentSmsBlock> listContent = new ArrayList<ContentSmsBlock>();
						listContent = (ArrayList<ContentSmsBlock>) db
								.getContentSmsBlocks(null, null, null, null, null);
						if (listContent.size() != 0) {
							for (int i = 0; i < listContent.size(); i++) {
								if (messageBody.contains(listContent.get(i)

										.getContent()))
									
								{

									blockModeSMS(getSettingDefaultModeSMS());
									return;
								}
							}

						}
					}
					//
					// block Header sms
					//
					if ((getSettingDefaultSMS() & 3) == 3) {
						if (db.getHeaderPhones("headerPhoneSms", null, null, null,
								null, null) != null) {
							ArrayList<HeaderPhone> ListHeader = new ArrayList<HeaderPhone>();
							ListHeader = (ArrayList<HeaderPhone>) db
									.getHeaderPhones("headerPhoneSms", null, null,
											null, null, null);
							for (int i = 0; i < ListHeader.size(); i++) {
								if (phoneNumber.contains(ListHeader.get(i)
										.getHeader())) {
									blockModeSMS(getSettingDefaultModeSMS());
									checkblock = 1;
									return;
								}
							}
						}
					}
				}
				if (checkblock == 1) {
					// date time
					Calendar cal = Calendar.getInstance();
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					String datetime = df.format(cal.getTime());
					// insert data
					SmsBlockedItem item = new SmsBlockedItem(phoneNumber,datetime, SmsBlockedItem.RECEIVE, messageBody);
					DatabaseHanler db1 = new DatabaseHanler(context);
					db1.insertSmsBlockItem(item);
					updateViewWhenReceiveSMS();
				}

			}catch(Exception e){
				e.printStackTrace();
			}
			
		}

	}

	/**
	 * call block black list
	 * 
	 * @param incomingNumber
	 *            : number call to phone
	 */
	private void BlockBlacklist(String incomingNumber) {
		DatabaseHanler db = new DatabaseHanler(mContext);
		ArrayList<BlackListItem> ListBlack = new ArrayList<BlackListItem>();
		ListBlack = (ArrayList<BlackListItem>) db.getBlackListItem(null, null,
				null, null, null);
		if (ListBlack.size() != 0) {
			for (BlackListItem PhoneNumber : ListBlack) {
				if (incomingNumber.contentEquals(PhoneNumber.getPhoneNumber())) {
					blockModeSMS(PhoneNumber.getMode());
					checkblock = 1;
				}
			}
		}
	}

	/**
	 * get default mode
	 * 
	 * @return
	 */
	private int getSettingDefaultSMS() {
		DatabaseHanler db = new DatabaseHanler(mContext);
		Setting item;
		item = db.getSetting(null);
		int mode = item.getBlockSmsSetting();
		return mode;
	}

	/**
	 * get mode sms
	 * 
	 * @param db
	 * @return
	 */
	private int getSettingDefaultModeSMS() {
		DatabaseHanler db = new DatabaseHanler(mContext);
		Setting item;
		item = db.getSetting(null);
		int mode = item.getDefaultModel();
		return mode;
	}

	private void blockModeSMS(int status) {
		DatabaseHanler db = new DatabaseHanler(mContext);
		switch (status & 15) {
		case 1:
			// delete all
			deleteSMS(mContext, messageBody, phoneNumber);
			break;
		case 2:
			// delete and save app
			deleteSMS(mContext, messageBody, phoneNumber);
			fInsertSMS(phoneNumber, messageBody, SmsBlockedItem.RECEIVE , db);
			saveapp = 1;
			updateViewWhenReceiveSMS();
			break;
		case 3:
			// save device1
			break;
		default:
			break;
		}
	}

	/**
	 * insert sms
	 */
	private void fInsertSMS(String phoneNumber, String messageBody, int status,
			DatabaseHanler dbh) {
		dbh.insertSmsBlockItem(new SmsBlockedItem(phoneNumber, dt.getTime()
				.toString(), status, messageBody));
	}

	/**
	 * Delete sms from inbox android
	 * 
	 * @param context
	 * @param message
	 * @param number
	 */
	public void deleteSMS(Context context, String message, String number) {
		try {

			abortBroadcast();
			// read and delete sms from inbox if not abort broadcast
			Thread.sleep(3000);
			Uri uriSms = Uri.parse("content://sms/inbox");
			Cursor c = context.getContentResolver().query(uriSms, null,
					"address" + " =? and " + "body" + " =?",
					new String[] { number, message }, "_id DESC");

			if (c != null && c.moveToFirst()) {
				do {
					long id = c.getLong(0);
					context.getContentResolver().delete(
							Uri.parse("content://sms/" + id), null, null);
					return;
				} while (c.moveToNext());
			}

		} catch (Exception e) {
			// mLogger.logError("Could not delete SMS from inbox: " +
			// e.getMessage());
			Toast.makeText(context, "Could not delete SMS from inbox",
					Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * smsblock Unknow contacts
	 * 
	 * @param incomingNumber
	 *            : number call to phone
	 */
	private void BlockUnknowContact(String incomingNumber) {
		Cursor CPhones;
		Cursor CSim;
		int CheckNumber = 0;// check phone number
		// Check contact phone
		CPhones = mContext.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				Phone.NUMBER + "=?", new String[] { incomingNumber }, null);// find
																			// incomingNumber
																			// in
																			// Contacts
		while (CPhones.moveToNext()) {
			String contactNumber = CPhones.getString(CPhones
					.getColumnIndex(Phone.NUMBER));
			if (incomingNumber.contentEquals(contactNumber)) {
				// have a number of Contact
				CheckNumber = 1;
			}
		}

		CPhones.close();// Close Cursor
		// Check contact SIM
		Uri simUri = Uri.parse("content://icc/adn");
		CSim = mContext.getContentResolver().query(simUri, null,
				Phone.NUMBER + "=?", new String[] { incomingNumber }, null);// find
																			// incomingNumber
																			// in
																			// sim
																			// Contacts
		while (CSim.moveToNext()) {
			String SimNumber = CSim.getString(CSim.getColumnIndex("number"));
			if (incomingNumber.contentEquals(SimNumber)) {
				// have a number of Contact
				CheckNumber = 1;
			}
		}
		CSim.close();// Close Cursor
		if (CheckNumber == 0) {
			DatabaseHanler db = new DatabaseHanler(mContext);
			blockModeSMS(getSettingDefaultModeSMS());
			checkblock = 1;
		}
	}
}
